package com.doyens.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.common.R;
import com.doyens.dto.DishDto;
import com.doyens.entity.Category;
import com.doyens.entity.Dish;
import com.doyens.entity.DishFlavor;
import com.doyens.service.CategoryService;
import com.doyens.service.DishFlavorService;
import com.doyens.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.jws.Oneway;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存数据
       /* Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //精确清除   精确清除某个分类下的菜品缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("菜品保存成功...");
    }


    @GetMapping("/page")
    public R<Page>  page(int page,int pageSize,String name){
        //按照以前的逻辑写
        //构造分页的构造器对象
        Page<Dish>  pageInfo = new Page<>(page,pageSize);
        //构造DTO的
        Page<DishDto> dishDtoPage = new Page<>();


        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询条件
        queryWrapper.like(name !=null,Dish::getName,name);
        //进行排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,queryWrapper);
        //数据拷贝   忽略这个数据, 因为我们后面要自己处理
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish>  records = pageInfo.getRecords();

        List<DishDto>  list =  records.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();

            //根据id去Category表里查询  分类信息
            Category category = categoryService.getById(categoryId);
            if (category !=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    //根据id查询菜品详情
    @GetMapping("/{id}")
    public R<DishDto>  get(@PathVariable("id") Long id ){
        //查询时候涉及到两张表数据
        DishDto  dishDto = dishService.getByIdWithFlavor(id);


        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    public R<String>  update(@RequestBody DishDto dishDto){
        log.info("修改菜品"+dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //数据存到redis一份


        //清理所有菜品的缓存数据
       /* Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        //精确清除   精确清除某个分类下的菜品缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功..");
    }

    //根据分类id查询菜品信息集合
   /* @GetMapping("/list")
    public R<List<Dish>>  queryByCategoryId(Long categoryId){
        LambdaQueryWrapper<Dish>  lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId !=null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.eq(Dish::getStatus,1);//状态是1, 在售的菜单
        //排序
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        return R.success(list);

    }*/
    //加口味的
    @GetMapping("/list")
    public R<List<DishDto>>  queryByCategoryId(Long categoryId,Integer status){
        // 1.先从缓存中取数据
        List<DishDto>  dishDtoList = null;
        //动态的key
        String key =  "dish_"+ categoryId +"_" +status; // dish_1397844263642378242_1

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);


        //2.判断 如果存在, 直接返回 不需要查询数据库
        if (dishDtoList !=null){
            return R.success(dishDtoList);
        }


        LambdaQueryWrapper<Dish>  lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(categoryId !=null,Dish::getCategoryId,categoryId);
        lambdaQueryWrapper.eq(Dish::getStatus,1);//状态是1, 在售的菜单
        //排序
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lambdaQueryWrapper);

        dishDtoList  = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId1 = item.getCategoryId();
            Category category = categoryService.getById(categoryId1);
            if (category != null) {  //分类名称
                dishDto.setCategoryName(category.getName());
            }
            //获取当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = new LambdaQueryWrapper<>();
            flavorQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(flavorQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //3.如果不存在,需要查询数据库,将查询到的数据,放到redis缓存中
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);


        return R.success(dishDtoList);

    }
}
